import * as React from 'react'
import { Table, Form, Input, Button, message } from 'antd'
import axios from '@/utils/axios'
import api from '@/api'

const FormItem = Form.Item

interface Props {
  dictCode: string;
}
@Form.create()
class DictDetail extends React.Component<Props> {
  constructor(props) {
    super(props)
    this.state = {
      editing: -1,
      loading: false,
      // curPage: 1,
      // total: 0,
      detailData: [],
    }
  }
  fetchData(){
    this.setState({
      loading: true
    })
    const reqParams = {
      dict_code: this.props.dictCode,
      // cur_page: this.state.curPage,
    }
    axios.post(api.configDict.detail, reqParams).then(res => {
      this.setState({
        detailData:res.data.list,
        loading: false,
        curPage: res.data.cur_page,
        total: res.data.total
      }) 
    })
  }
  handleSubmit = e => {
    e.preventDefault()
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (err) {
        console.error(err)
      }
      axios.post(api.customer.add, values).then(res => {
        if (res.data.code === 200) {
          this.props.form.resetFields()
          message.info('创建成功')
        } else {
          message.error(res.data.msg)
        }
      })
    })
  }

  renderFormItem() {
    const { getFieldDecorator } = this.props.form
    const that = this
    const formList = [
      { key: 'id', label: '序号',
        render: (item, index) => {
          return (
            <span>{that.state.curPage * 10 + index+1}</span>
          )
        }
      },
      { key: 'key_code', label: '字典编码',
        rule: [ {required: true }],
      },
      { key: 'key_name', label: '字典名称',
        rule: [ {required: true }],
      },
      { key: 'operator', label: '维护', 
        render: (item, index)=> {
          return (
            <Button type="primary"
              onClick={()=>this.editing = index}
            >维护</Button>
          )
        }
      },
    ]

    const res = []
    formList.forEach((item, index) => {
      res.push(
        <FormItem
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 14 }}
          label={item.label}
          key={item.key}
        >
          {this.state.editing === index
             ? getFieldDecorator(item.key, {rules: item.rules })(<Input />)
             : item.render
             ? item.render(item, index)
             : <span>{this.state.detailData[item.key]}</span>
          }
        </FormItem>
      )
    })
    return res
  }
  componentWillReceiveProps(newProps){
    if(newProps.dictCode != this.props.dictCode) {
      this.fetchData()
    }
  }

  componentDidMount() {
    this.fetchData()
  }
  render() {
    return (
      <Table
        bordered
        dataSource={this.state.detailData}
        columns={this.columns}
      />
   )
  }
}
export default DictDetail
